package com.z.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import com.z.config.ConfigReader;

public class AttachUtil {
	private static AttachUtil attachUtil;
	public static AttachUtil getInstance(){
		if(attachUtil==null){
			attachUtil=new AttachUtil();
		}
		return attachUtil;
	}
	
	/**
	 * 保存
	 * 
	 * @param file
	 *            文件对象
	 * @return
	 */
	public String save(File file,String extend) {
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(file);
			byte[] bytes = new byte[fileInputStream.available()];
			fileInputStream.read(bytes, 0, bytes.length);
			return save(bytes,extend);
		} catch (Exception e) {
			return null;
		} finally {
			try {
				fileInputStream.close();
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 保存
	 * 
	 * @param bytes
	 *            内容
	 * @return
	 */
	public String save(byte[] bytes,String extend) {
		Date now = new Date(System.currentTimeMillis());
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(now);
		String root = ConfigReader.getInstance().getAttachRoot();
		String year = String.valueOf(calendar.get(Calendar.YEAR));
		String month = String.valueOf(calendar.get(Calendar.MONTH));

		String path = year + "/" + month + "/";
		File folder = new File(root + path);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		String ext=extend==null?"dat":extend;
		path += UUID.randomUUID().toString() + "."+ext;
		File f = new File(root + path);
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream(f);
			fileOutputStream.write(bytes, 0, bytes.length);
			return path;
		} catch (Exception e) {
			return null;
		} finally {
			try {
				fileOutputStream.close();
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 读取
	 * 
	 * @param path
	 *            数据库中记录的相对路径
	 * @return
	 */
	public byte[] read(String path) {
		String root = ConfigReader.getInstance().getAttachRoot();
		File file = new File(root + path);
		if (file.exists()) {
			FileInputStream fileInputStream = null;
			try {
				fileInputStream = new FileInputStream(file);
				byte[] bytes = new byte[fileInputStream.available()];
				fileInputStream.read(bytes, 0, bytes.length);
				return bytes;
			} catch (Exception e) {
			} finally {
				try {
					fileInputStream.close();
				} catch (IOException e) {
				}
			}
		}
		return null;
	}
}
